import { useRequest } from 'ahooks'

import { useControllerRef } from '@/hooks/useAbortController'
import { useRequestSyncStorePlugin } from '@/hooks/useRequestSyncStorePlugin'
import { useUrlParams } from '../utils'
import { apiGetAttachmentList } from './apis'
import { IAttachmentListItem } from './interface'
import { useBoundStore } from './store'

export const useAttachmentList = () => {
  const { waybillNo } = useUrlParams()

  const controllerRef = useControllerRef()
  const requestSyncStorePlugin = useRequestSyncStorePlugin({
    onMaybeChange: request => useBoundStore.setState({ request }),
  })

  useRequest<IAttachmentListItem[], []>(
    () => {
      controllerRef.current.abort()
      controllerRef.current = new AbortController()
      return apiGetAttachmentList(waybillNo, controllerRef.current.signal)
    },
    {},
    [requestSyncStorePlugin],
  )
}
